from __future__ import division

'''
Created on Nov 30, 2011

@author: anorberg
'''

import sys
import loadResultTable
import golemize

def convertOneRecord(record):
    return  {
               'NResults'   : int(record['NResults']),
               'KS'         : float(record['KS']),
               'Dispersion' : float(record['FlatDispersion']),
               'Unimodality': float(record['FlatUnimodality']),
               'TotalMean'  : float(record['TotalMean'])
            }

class bucketBrigade(dict):
    def push(self, key, value):
        if key in self:
            existingValue = self[key]
            try:
                existingValue.append(value)
                return existingValue
            except AttributeError:
                #presumably, that wasn't an appendable sequence
                asList = [existingValue, value]
                self[key] = asList
                return asList
        else:
            that = [value]
            self[key] = that
            return that


def dumpResults(outputFile, targetResults):
    print >> outputFile, "\t".join(HEADER)
    for result in targetResults:
        print >> outputFile, "\t".join((str(thing) for thing in result))
    
    outputFile.flush()

def main(inFileName, outFileName):
    table = loadResultTable.loadResultTable(inFileName)
    outputTarget = open(outFileName+".targets", "w")
    outputPredictor = open(outFileName+".predictors", "w")
    asTarget = bucketBrigade()
    asPredictor = bucketBrigade()
    for record in table:
        converted = convertOneRecord(record)
        asTarget.push(record['Target'], converted)
        asPredictor.push(record['Predictor'], converted)
    golemizer = golemize.jsonToGolemizer(open("enhancedExceptionGlados.json", "r"))
    golemizer.setTaskSize(20)
    
    targetResults = golemizer.goDoIt(asTarget.iteritems(), None, aggregate,
                                        binplace = False, #imports local stuff
                                        label="RF-ACE-Aggregator meta-aggregator",
                                        email="anorberg@systemsbiology.org")
    del asTarget
    dumpResults(outputTarget, targetResults)
    outputTarget.close()
    del outputTarget
    del targetResults
    
    predictorResults = golemizer.goDoIt(asPredictor.iteritems(), None, aggregate,
                                        binplace = False, #imports local stuff
                                        label="RF-ACE-Aggregator meta-aggregator",
                                        email="anorberg@systemsbiology.org")
    del asPredictor
    dumpResults(outputPredictor, predictorResults)
    outputPredictor.close()
    del outputPredictor
    del predictorResults

HEADER = ['Feature', 'Instances', 'AvgMatches', 'AvgKS', 'AvgDispersion',
          'AvgUnimodality', 'AvgImportance']

def aggregate(nameRecordsTuple, ignored):
    result = nameRecordsTuple[0]
    instances = 0
    totalHits = 0
    totalKs = 0.0
    totalDispersion = 0.0
    totalUnimodality = 0.0
    totalImportance = 0.0
    
    for record in nameRecordsTuple[1]:
        instances += 1
        totalHits += record['NResults']
        totalKs += record['KS']
        totalDispersion += record['Dispersion']
        totalUnimodality += record['Unimodality']
        totalImportance += record['TotalMean']
        
    return (result, instances, totalHits/instances, totalKs/instances,
            totalDispersion/instances, totalUnimodality/instances, totalImportance/instances)

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])